package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.mapper.TravelContentMapper;
import cn.wolfcode.luowowo.article.mapper.TravelMapper;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.common.query.TravelQueryObject;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelMapper travelMapper;

    @Autowired
    private TravelContentMapper travelContentMapper;

    /**
     * 攻略文章管理的分页
     *
     * @param qo
     * @return
     */
    public PageInfo query(TravelQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<Travel> list = travelMapper.selectForList(qo);
        return new PageInfo(list);
    }

    /**
     * 根据id查询文章
     *
     * @param id
     * @return
     */
    public Travel get(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据id查询文章内容
     *
     * @param id
     * @return
     */
    public TravelContent getContent(Long id) {
        return travelContentMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询点击量前三的游记
     *
     * @param destId
     * @return
     */
    public List<Travel> listViewunmTop3(Long destId) {
        return travelMapper.selectViewunmTop3(destId);
    }

    /**
     * 游记的保存和更新操作
     * @param entity
     */
    public AjaxResult saveOrUpdate(Travel entity) {

        AjaxResult result = new AjaxResult();
        //先拿到游记的内容
        TravelContent content = entity.getTravelContent();
        //生成摘要
        entity.setSummary("....AI加载中....");
        //设置更新时间
        entity.setLastUpdateTime(new Date());
        //判断是添加还是更新
        if (entity.getId() == null) {
            //设置发布时间
            entity.setReleaseTime(new Date());
            //设置发布状态
            entity.setState(Travel.STATE_RELEASE);
            ///设置创建时间
            entity.setCreateTime(new Date());
            //添加游记信息和游记内容的操作
            travelMapper.insert(entity);
            content.setId(entity.getId());
            travelContentMapper.insert(content);
        } else {
            //更新游记的信息
            travelMapper.updateByPrimaryKey(entity);
            //拿到id更新游记的内容
            content.setId(entity.getId());
            travelContentMapper.updateByPrimaryKey(content);
        }
        //返回一个AjaxResult对象,记得使用addData把数据添加进去
        return result.addData(entity.getId());
    }

    public List<Travel> list() {
        return travelMapper.selectAll();
    }

}
